<?php
/**
 * Created by PhpStorm.
 * User: wenqiang.yq@gmail.com
 * Date: 16-2-29
 * Time: 下午9:57
 */

namespace ElasticSearch;


class EsHttp
{
    const TYPE_HEAD = "HEAD";
    const TYPE_PUT = "PUT";
    const TYPE_DELETE = "DELETE";
    const TYPE_GET = "GET";
    const TYPE_POST = "POST";

    /**
     * 以PUT的方式提交数据
     * @param $url
     * @param $data
     * @return mixed|string
     */
    static function put($url, $data="")
    {
        return self::query($url, $data, self::TYPE_PUT);
    }

    /**
     * 以DELETE的方式提交数据
     * @param $url
     * @return mixed|string
     */
    static function delete($url)
    {
        return self::query($url, "", self::TYPE_DELETE);
    }

    /**
     * 以GET的方式提交数据
     * @param $url
     * @param $data
     * @return mixed|string
     */
    static function get($url, $data = "")
    {
        return self::query($url, $data, self::TYPE_GET);
    }

    /**
     * 以POST的方式提交数据
     * @param $url
     * @param $data
     * @return mixed|string
     */
    static function post($url, $data)
    {
        return self::query($url, $data, self::TYPE_POST);
    }

    /**
     * 以HEAD的方式提交数据
     * @param $url
     * @return mixed|string
     */
    static function head($url)
    {
        return self::query($url, "", self::TYPE_HEAD);
    }

    /**
     * curl访问库
     * @param $url
     * @param $data
     * @param string $type
     * @return mixed|string
     */
    static function query($url, $data, $type = self::TYPE_POST)
    {
        $type = strtoupper($type);
        if (!is_string($data)) {
            $data = json_encode($data);
        }
        $ch = curl_init($url);
        curl_setopt_array($ch, array(
            CURLOPT_CUSTOMREQUEST => $type,
            CURLOPT_POSTFIELDS => $data,
            CURLOPT_RETURNTRANSFER => 1,
            CURLOPT_HEADER => true,
            CURLOPT_NOBODY => false,
            CURLOPT_HTTPHEADER => array(
                "Accept-Encoding:gzip"
            )
        ));
        $response = curl_exec($ch);
        $headerSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
        $header = substr($response, 0, $headerSize);
        if ($type == self::TYPE_HEAD) {
            return $header;
        }
        $body = substr($response, $headerSize);
        $zip = 0;
        if (strpos($header, 'gzip')) {
            $zip = 1;
            $ret = gzdecode($body);
        } else {
            $ret = $body;
        }
        $ret = json_decode($ret, 1);
        $ret['zip'] = $zip;
        return $ret;
    }
}